package com.hdhere.core.security.shiro;

import com.alibaba.fastjson.JSON;
import com.hdhere.core.rest.ErrorObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*******************************************************************************************
 *
 *
 * @author: dustin
 * @date: 2019-08-15 16:39
 * @Description:
 * @version 1.0
 *
 *******************************************************************************************
 */
public class AccessResponse {

    public static void onDenied(ServletRequest request, ServletResponse response) throws IOException {

        HttpServletRequest httpRequest = (HttpServletRequest)request;
        //判断是否ajax请求，返回json数据或重定向到登录页
        boolean isAjaxRequest = !StringUtils.isBlank(httpRequest.getHeader("x-requested-with"))
                && httpRequest.getHeader("x-requested-with").equals("XMLHttpRequest");
        if(isAjaxRequest){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            String result = JSON.toJSONString(ErrorObject.error(ErrorObject.ErrorCode.LOGIN_ERROR,
                    "Please login first."));
            httpResponse.getOutputStream().write(result.getBytes());
            httpResponse.setContentType("application/json;charset=utf-8");
            httpResponse.setStatus(HttpStatus.NOT_IMPLEMENTED.value());
        }else
            WebUtils.issueRedirect(request, response, "/403");
    }
}
